package com.zyylr.classroomreservationsystem.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.widget.PullRefreshLayout;
import com.diegodobelo.expandingview.ExpandingItem;
import com.diegodobelo.expandingview.ExpandingList;
import com.zyylr.classroomreservationsystem.R;
import com.zyylr.classroomreservationsystem.activity.ShowFreeTimeActivity;
import com.zyylr.classroomreservationsystem.bean.Building;
import com.zyylr.classroomreservationsystem.bean.Classroom;
import com.zyylr.classroomreservationsystem.bean.Msg;
import com.zyylr.classroomreservationsystem.web.IClassroom;
import com.zyylr.classroomreservationsystem.web.RetrofitFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class ClassroomToTimeFragment extends Fragment {
    private Button button_free_time;

    private static final String TAG = "classroom2timeFragment";
    private ExpandingList buildingExpandingList;
    private PullRefreshLayout pullRefreshLayout;
    private List<Building> buildings;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_classroom_to_time, container, false);
        return root;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        buildingExpandingList = getActivity().findViewById(R.id.expanding_list_all_classrooms);
        pullRefreshLayout = getActivity().findViewById(R.id.swipeRefreshLayout_not_audited);
        pullRefreshLayout.setRefreshStyle(PullRefreshLayout.STYLE_WATER_DROP);

        pullRefreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pullRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        buildingExpandingList.removeAllViews();
                        sendHttpRequest();
                    }
                }, 0);

            }
        });
        pullRefreshLayout.setRefreshing(true);
        sendHttpRequest();
    }

    /**
     * 通过retrofit框架发送http请求，将得到的数据存在buildings中
     */
    private void sendHttpRequest() {
        Retrofit retrofit = RetrofitFactory.getRetrofit();
        IClassroom request = retrofit.create(IClassroom.class);
        Call<Msg<List<Building>>> call = request.getAllClassrooms();
        call.enqueue(new Callback<Msg<List<Building>>>() {
            @Override
            public void onResponse(Call<Msg<List<Building>>> call, Response<Msg<List<Building>>> response) {
                Msg msg = response.body();
                Log.d(TAG, "msg= " + msg);
                try {
                    assert msg != null;
                    //登录错误，toast错误信息
                    if (msg.getCode() == 200) {
                        Toast.makeText(getContext(), msg.getMsg(), Toast.LENGTH_SHORT).show();
                        pullRefreshLayout.setRefreshing(false);
                        return;
                    }
                    buildings = (List<Building>) msg.getExtend().get("buildings");
                    addItems();
                } catch (Exception e) {
                    Toast.makeText(getContext(), "数据解析错误！", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, e.getMessage());
                } finally {
                    pullRefreshLayout.setRefreshing(false);
                }
            }

            @Override
            public void onFailure(Call<Msg<List<Building>>> call, Throwable t) {
                Toast.makeText(getContext(), "服务请求错误！", Toast.LENGTH_SHORT).show();
                pullRefreshLayout.setRefreshing(false);
            }
        });
    }

    /**
     * 为buildingExpandingList添加数据
     */
    private void addItems() {
        for (Building building : buildings) {
            //createBuildingItems(building);
            List<Classroom> classrooms = building.getClassrooms();
//            ArrayList<String> classroomNames = new ArrayList<>();

            //有序的hashmap,存放classroom id和name
            LinkedHashMap<Integer, String> classroomNameMap = new LinkedHashMap<>();
            for (Classroom classroom : classrooms) {
                classroomNameMap.put(classroom.getId(), classroom.getName());
            }
            int buildingColorRes, buildingIconRes;
            switch (building.getId()) {
                case 1:
                    buildingColorRes = R.color.blue;
                    buildingIconRes = R.drawable.building_boyuelou;
                    break;
                case 2:
                    buildingColorRes = R.color.green;
                    buildingIconRes = R.drawable.building_yifulou;
                    break;
                case 3:
                    buildingColorRes = R.color.purple;
                    buildingIconRes = R.drawable.building_gongxinglou;
                    break;
                case 4:
                    buildingColorRes = R.color.yellow;
                    buildingIconRes = R.drawable.building_lvzhilou;
                    break;
                default:
                    buildingColorRes = R.color.blue;
                    buildingIconRes = R.drawable.building_boyuelou;
                    break;
            }
            addItem(building.getName(), classroomNameMap, buildingColorRes, buildingIconRes);
        }
    }

    /**
     * 给父item添加子item
     *
     * @param title
     * @param subItems
     * @param colorRes
     * @param iconRes
     */
    private void addItem(String title, LinkedHashMap<Integer, String> subItems, int colorRes, int iconRes) {
        final ExpandingItem item = buildingExpandingList.createNewItem(R.layout.expanding_layout_building);

        if (item != null) {
            item.setIndicatorColorRes(colorRes);
            item.setIndicatorIconRes(iconRes);

            ((TextView) item.findViewById(R.id.tv_building)).setText(title);

            item.createSubItems(subItems.size());
            Iterator it = subItems.entrySet().iterator();

            for (int i = 0; i < item.getSubItemsCount(); i++) {
                final View view = item.getSubItemView(i);
                TextView tv_classroom = view.findViewById(R.id.tv_classroom);
                Map.Entry entry = (Map.Entry) it.next();
                //给textView设置额外的数据，这个数据是classroom的id
                tv_classroom.setTag(entry.getKey());
                tv_classroom.setText((String) entry.getValue());
                addSubItemClickListener(tv_classroom);
            }
        }
    }

    /**
     * 给教室item添加按键监听
     * 跳转到空闲时间显示活动
     *
     * @param viewClassroom classroom的view
     */
    private void addSubItemClickListener(TextView viewClassroom) {
        viewClassroom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String classroomName = ((TextView) v).getText().toString();
                Integer classroomId = (Integer) v.getTag();
                Intent intent = new Intent(getActivity(), ShowFreeTimeActivity.class);
                intent.putExtra("classroomId", classroomId);
                intent.putExtra("classroomName", classroomName);
                startActivity(new Intent(getActivity(), ShowFreeTimeActivity.class));
            }
        });
    }
}
